// src/pages/Dashboard/Dashboard.tsx
import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Progress, Table, Button, Space, Tag } from 'antd';
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  PoweroffOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import { useDomainStore } from '../../stores/domainStore';
import { usePolling } from '../../hooks/usePolling';
import { domainsApi } from '../../api/domains';
import type { Domain } from '../../api/types';

const Dashboard: React.FC = () => {
  const { domains, fetchDomains, startDomain, shutdownDomain, loading } = useDomainStore();
  const [refreshing, setRefreshing] = useState(false);

  // 初始加载和轮询
  useEffect(() => {
    fetchDomains();
  }, [fetchDomains]);

  usePolling(
    async () => {
      await fetchDomains();
    },
    { interval: 5000, enabled: true }
  );

  // 统计数据
  const stats = {
    total: domains.length,
    running: domains.filter((d) => d.state === 'running').length,
    paused: domains.filter((d) => d.state === 'paused').length,
    shutoff: domains.filter((d) => d.state === 'shutoff').length,
  };

  // 手动刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchDomains();
    setRefreshing(false);
  };

  // 状态标签
  const getStateTag = (state: string) => {
    const stateConfig: Record<string, { color: string; text: string }> = {
      running: { color: 'success', text: '运行中' },
      paused: { color: 'warning', text: '已暂停' },
      shutoff: { color: 'default', text: '已关机' },
      crashed: { color: 'error', text: '崩溃' },
      suspended: { color: 'processing', text: '已挂起' },
    };
    const config = stateConfig[state] || { color: 'default', text: state };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      width: 120,
      render: (state: string) => getStateTag(state),
    },
    {
      title: 'CPU',
      dataIndex: 'vcpus',
      key: 'vcpus',
      width: 100,
      render: (vcpus: number) => `${vcpus} vCPU`,
    },
    {
      title: '内存',
      dataIndex: 'memory',
      key: 'memory',
      width: 150,
      render: (memory: number) => `${(memory / 1024).toFixed(1)} GB`,
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_: any, record: Domain) => (
        <Space size="small">
          {record.state === 'shutoff' ? (
            <Button
              type="link"
              icon={<PlayCircleOutlined />}
              onClick={() => startDomain(record.name)}
            >
              启动
            </Button>
          ) : record.state === 'running' ? (
            <>
              <Button
                type="link"
                icon={<PauseCircleOutlined />}
                onClick={() => useDomainStore.getState().suspendDomain(record.name)}
              >
                暂停
              </Button>
              <Button
                type="link"
                danger
                icon={<PoweroffOutlined />}
                onClick={() => shutdownDomain(record.name)}
              >
                关机
              </Button>
            </>
          ) : record.state === 'paused' ? (
            <Button
              type="link"
              icon={<PlayCircleOutlined />}
              onClick={() => useDomainStore.getState().resumeDomain(record.name)}
            >
              恢复
            </Button>
          ) : null}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="虚拟机总数"
              value={stats.total}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="运行中"
              value={stats.running}
              valueStyle={{ color: '#52c41a' }}
              prefix={<PlayCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已暂停"
              value={stats.paused}
              valueStyle={{ color: '#faad14' }}
              prefix={<PauseCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已关机"
              value={stats.shutoff}
              valueStyle={{ color: '#8c8c8c' }}
              prefix={<PoweroffOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 虚拟机列表 */}
      <Card
        title="虚拟机列表"
        extra={
          <Button
            icon={<SyncOutlined spin={refreshing} />}
            onClick={handleRefresh}
            loading={refreshing}
          >
            刷新
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={domains}
          rowKey="uuid"
          loading={loading}
          pagination={{ pageSize: 10 }}
          onRow={(record) => ({
            onClick: () => {
              // 跳转到详情页
              window.location.href = `/vms/${record.name}`;
            },
            style: { cursor: 'pointer' },
          })}
        />
      </Card>
    </div>
  );
};

export default Dashboard;